package com.chen106106.sstest.common;

import org.apache.log4j.Logger;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

public class JSONUtils {
	
	private static Logger log = Logger.getLogger(JSONUtils.class);
	@SuppressWarnings("unchecked")
	public static  Map<String,Object>  jsonToMap(String json){
		if(json==null||"".equals(json.trim()))
		return null;
		JSONObject jsonobject=JSONObject.fromObject(json);
		Set<String> jsonSet=jsonobject.keySet();
		Map<String,Object> revalue=new HashMap<String,Object>();
		for(String key:jsonSet){
			revalue.put(key, jsonobject.get(key));
		}
		return revalue;
	}
	
	@SuppressWarnings("unchecked")
	public static void ajaxWrite(HttpServletResponse response,String json){
		response.setCharacterEncoding("utf-8");
		response.setContentType("application/json");
		PrintWriter out = null;
		try {
			out = response.getWriter();
			out.write(json);
			
		} catch (IOException e) {
			log.error(e.getMessage(),e);
		}finally{
			if(null!=out){
				out.flush();
				out.close();
			}
		}
	}
}
